之前的章節有基礎地學習過URLSession,以URLSession將API下載下來後,再進行JSON的處理,在Swift4中有新增加JSONDecoder以及Codable,可以不用像以往層層頗析JSON或者是利用第三方函式庫。
以下是練習用的API:
http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors
利用Online JSON Viewer可以看到結構:
2. 實作部分:
class Actors: Codable{
let actors:[Actor]
init(actors: [Actor]) {
self.actors = actors
}
}
class Actor: Codable {
let name: String
let des: String
let dob: String
let country: String
let height: String
let spouse: String
let children: String
let image: String
init(name: String, des: String, dob: String, country: String, height: String, spouse: String, children: String, image: String) {
self.name = name
self.des = des
self.dob = dob
self.country = country
self.height = height
self.spouse = spouse
self.children = children
self.image = image
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var actors = [Actor]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let actorCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ActorTableViewCell
actorCell.nameLabel.text = actors[indexPath.row].name
actorCell.heightLabel.text = actors[indexPath.row].height
return actorCell
}
@IBOutlet weak var actorTableView: UITableView!
let apiAddress = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
override func viewDidLoad() {
super.viewDidLoad()
actorTableView.delegate = self
actorTableView.dataSource = self
downloadJSOn(webAddress: apiAddress)
}
//以URLSession來下載
func downloadJSOn(webAddress:String){
if let url = URL(string: webAddress){
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, URLResponse, error) in
if error != nil{
print("Something is wrong")
return
}
if let downloadedData = data{
do{
let decoder = JSONDecoder()
let downloadedActors = try decoder.decode(Actors.self, from: downloadedData)
self.actors = downloadedActors.actors
DispatchQueue.main.async {
self.actorTableView.reloadData()
}
}
catch{
print("something wrong after downloaded")
}
}
})
task.resume()
}
}
}
但結果卻不如預想能夠在TableView產生演員的名字及身高,而是空白的一片,再來找找bug是出現在哪邊,一樣的寫法只是把api換成另外一個,結果有顯示出來。但還是會再做一次確認。